<!DOCTYPE html>
<html lang="zh-CN" class="loading">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>MicroPython优雅的实现中断 - Skyone-Blog</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="Python,micropython,"> 
    <meta name="description" content="Skyone技术博客,中断就像它的声音一样，是一个 “中断 “程序正常流程的事件。在一般的情况下，我们处理的是外部硬件中断，这意味着在程序继续运行之前，需要处理一个信号或状态变化。基本方法虽然简单，但略显发杂，代码比较乱，我们可以使用Python装饰器优雅的实现中断。"> 
    <meta name="author" content="王志伟"> 
    <link rel="alternative" href="atom.xml" title="Skyone-Blog" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">

    
<link rel="stylesheet" href="/css/diaspora.css">

    <!-- 看板娘
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css">
    <script src="/live2d-widget/autoload.js"></script>
    -->
    <!-- MD5 -->
    <script src="/js/md5.min.js"></script>
    <!-- MathJax -->
    
        <script type="text/x-mathjax-config">
        (function () {
            let target = document.getElementsByClassName("content")[0];
            MathJax.Hub.Config({
                tex2jax: {
                    inlineMath:  [ ["$", "$"] ],
                    displayMath: [ ["$$","$$"] ],
                    skipTags: ['script', 'noscript', 'style', 'textarea', 'pre','code','a'],
                    ignoreClass:"class1"
                }
            });
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,target]);
        })();
    </script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>

    
<meta name="generator" content="Hexo 5.3.0"></head>

<body class="loading">
    <span id="config-title" style="display:none">Skyone-Blog</span>
    <div id="loader"></div>
    <div id="single">
    <div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <a class="iconfont icon-home image-icon" href="javascript:;" data-url="https://www.skyone.host"></a>
    <div title="播放/暂停" class="iconfont icon-play"></div>
    <h3 class="subtitle">MicroPython优雅的实现中断</h3>
    <div class="social">
        <div>
            <div class="share">
                <a title="获取二维码" class="iconfont icon-scan" href="javascript:;"></a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
</div>

    <div class="section">
        <div class="article">
    <div class='main'>
        <h1 class="title">MicroPython优雅的实现中断</h1>
        <div class="stuff">
            <span>五月 13, 2021</span>
            
  <ul class="post-tags-list" itemprop="keywords"><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/Python/" rel="tag">Python</a></li></ul>


        </div>
        <div class="content markdown">
            <p>中断就像它的声音一样，是一个 “中断 “程序正常流程的事件。在一般的情况下，我们处理的是外部硬件中断，这意味着在程序继续运行之前，需要处理一个信号或状态变化。</p>
<h2 id="中断的基本实现方法"><a href="#中断的基本实现方法" class="headerlink" title="中断的基本实现方法"></a>中断的基本实现方法</h2><p>为了实现中断，我们需要将一个引脚定义为 “中断输入”， 定义该点上的状态变化被认为是一个中断。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> machie</span><br><span class="line"></span><br><span class="line"><span class="built_in">int</span> = machine.Pin(<span class="number">1</span>, machine.Pin.IN, machine.Pin.PULL_DOWN)</span><br><span class="line"><span class="comment"># 1 号引脚，输入模式，下拉电阻</span></span><br></pre></td></tr></table></figure>
<p>同时，还需要创建了一个 “中断处理程序 “函数，我们希望在检测到中断时运行该函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">interrupt_handler</span>(<span class="params">pin</span>):</span></span><br><span class="line">    <span class="comment"># 参数 `pin` 代表触发该中断的引脚</span></span><br><span class="line">    print(<span class="string">&quot;%d号引脚触发中断！&quot;</span> % pin)</span><br></pre></td></tr></table></figure>
<p>然后将 “中断处理程序 “与 “中断输入 “配对。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">int</span>.irq(trigger=machine.Pin.IRQ_RISING, handler=interrupt_handler)</span><br></pre></td></tr></table></figure>
<p>现在，每当中断输入条件发生时，Pico 将停止它正在做的任何事情，并执行 “中断处理程序”。然后它将恢复到原来的位置。</p>
<p>完整代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> machie</span><br><span class="line"><span class="keyword">import</span> utime</span><br><span class="line"></span><br><span class="line">high = machine.Pin(<span class="number">0</span>, machine.Pin.OUT)</span><br><span class="line">high.value(<span class="number">1</span>)</span><br><span class="line">int_pin = machine.Pin(<span class="number">1</span>, machine.Pin.IN, machine.Pin.PULL_DOWN)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">interrupt_handler</span>(<span class="params">pin</span>):</span></span><br><span class="line">    print(<span class="string">&quot;%s触发中断！&quot;</span> % <span class="built_in">str</span>(pin))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">int_pin.irq(trigger=machine.Pin.IRQ_RISING, handler=interrupt_handler)</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    print(<span class="string">&quot;Running!&quot;</span>)</span><br><span class="line">    utime.sleep(<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>运行这个脚本</p>
<p>在<code>0</code>号引脚和<code>1</code>号引脚间连接一个开关，当按下这个开关时，即打印</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Pin(<span class="number">1</span>, mode=IN, pull=PULL_DOWN)触发中断！</span><br></pre></td></tr></table></figure>
<p>细心的朋友应该发现了，按钮按一次，中断会触发多次，我们可以通过判断中断与上一次中断的时间来决定是否执行中断函数，这部分非常简单，大家自己改改就行了。</p>
<h2 id="优雅的实现中断"><a href="#优雅的实现中断" class="headerlink" title="优雅的实现中断"></a>优雅的实现中断</h2><p>上面基本方法虽然简单，但略显发杂，代码比较乱，下面让我们使用<a href="https://www.skyone.host/2021/01/17/python-zhuang-shi-qi/">Python装饰器</a>封装一个中断实现。</p>
<p>如果你对装饰器不了解，你仍然可以使用该方法，但如果想自己DIY的话，可以看看我的<a href="https://www.skyone.host/2021/01/17/python-zhuang-shi-qi/">这篇文章</a></p>
<p>创建<code>interrupt.py</code>，内容如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> machine</span><br><span class="line"><span class="keyword">import</span> utime</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Interrupt</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self,</span></span></span><br><span class="line"><span class="function"><span class="params">                 pin,</span></span></span><br><span class="line"><span class="function"><span class="params">                 pull=machine.Pin.PULL_DOWN,</span></span></span><br><span class="line"><span class="function"><span class="params">                 trigger=machine.Pin.IRQ_RISING,</span></span></span><br><span class="line"><span class="function"><span class="params">                 time=<span class="number">1000</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">                 before=<span class="literal">None</span>,</span></span></span><br><span class="line"><span class="function"><span class="params">                 final=<span class="literal">None</span></span>):</span></span><br><span class="line">        self.pin = machine.Pin(pin, machine.Pin.IN, pull)</span><br><span class="line">        self.trigger = trigger</span><br><span class="line">        self.time = time</span><br><span class="line">        self.last_time = utime.ticks_ms()</span><br><span class="line">        self.before = before</span><br><span class="line">        self.final = final</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span>(<span class="params">self, func</span>):</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">wrapped_func</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">            <span class="keyword">if</span> self.before <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                self.before()</span><br><span class="line">            this_time = utime.ticks_ms()</span><br><span class="line">            res = <span class="literal">None</span></span><br><span class="line">            <span class="keyword">if</span> this_time - self.last_time &gt; self.time:</span><br><span class="line">                self.pin.irq(handler=<span class="literal">None</span>)</span><br><span class="line">                res = func(*args, **kwargs)</span><br><span class="line">                self.pin.irq(handler=wrapped_func)</span><br><span class="line">                self.last_time = this_time</span><br><span class="line">            <span class="keyword">if</span> self.final <span class="keyword">is</span> <span class="keyword">not</span> <span class="literal">None</span>:</span><br><span class="line">                self.final()</span><br><span class="line">            <span class="keyword">return</span> res</span><br><span class="line">        self.pin.irq(trigger=self.trigger, handler=wrapped_func)</span><br><span class="line">        <span class="keyword">return</span> wrapped_func</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>相信了解Python装饰器的朋友应该能看懂这个类的工作原理</p>
<p>下面我再写一个中断的示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> machine</span><br><span class="line"><span class="keyword">import</span> utime</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> interrupt <span class="keyword">import</span> Interrupt</span><br><span class="line"></span><br><span class="line">high = machine.Pin(<span class="number">0</span>, machine.Pin.OUT)</span><br><span class="line">high.value(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@Interrupt(<span class="params"><span class="number">1</span>, time=<span class="number">300</span></span>)</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handler</span>(<span class="params">pin</span>):</span></span><br><span class="line">    print(<span class="string">&quot;Interrupt Detected!&quot;</span>)</span><br><span class="line">    print(<span class="string">&quot;%s触发中断！&quot;</span> % <span class="built_in">str</span>(pin))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    print(<span class="string">&quot;Running!&quot;</span>)</span><br><span class="line">    utime.sleep(<span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p>是不是清爽很多？</p>
<p><code>@Interrupt()</code>可以有6个参数，分别为：</p>
<ul>
<li><p><code>pin</code></p>
<p>表示由于中断的引脚ID，必填</p>
</li>
<li><p><code>pull</code></p>
<p>表示电阻是上拉还是下拉，选填</p>
</li>
<li><p><code>trigger</code></p>
<p>表示当引脚电位如何变化时触发中断，选填</p>
</li>
<li><p><code>time</code></p>
<p>表示两次触发中断的最短时间，选填</p>
</li>
<li><p><code>before</code></p>
<p>表示执行中断函数前执行的函数，注意不论是否满足最短间隔时间都会执行，选填</p>
</li>
<li><p><code>final</code></p>
<p>表示执行中断函数后执行的函数，注意不论是否满足最短间隔时间都会执行，选填</p>
</li>
</ul>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls" data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
                <ul id="audio-list" style="display:none">
                    
                        
                            <li title='0' data-url='https://tc.skyone.host/blog/music/%E6%B4%9B%E5%A4%A9%E4%BE%9D%20-%20%E5%A4%9C%E8%88%AA%E6%98%9F.flac'></li>
                        
                    
                        
                            <li title='1' data-url='https://tc.skyone.host/blog/music/%E6%B4%9B%E5%A4%A9%E4%BE%9D%20-%20%E8%8C%89%E8%8E%89%E8%8A%B1.mp3'></li>
                        
                    
                        
                            <li title='2' data-url='https://tc.skyone.host/blog/music/%E8%B5%A4%E7%BE%BD%20-%20%E4%B8%87%E5%8F%A4%E7%94%9F%E9%A6%99.flac'></li>
                        
                    
                        
                            <li title='3' data-url='https://tc.skyone.host/blog/music/%E6%B4%9B%E5%A4%A9%E4%BE%9D%20-%20%E4%B8%BA%E8%B0%81%E8%80%8C%E4%B8%BA.mp3'></li>
                        
                    
                        
                            <li title='4' data-url='https://tc.skyone.host/blog/music/%E4%B9%90%E6%AD%A3%E7%BB%AB%20-%20Faded.mp3'></li>
                        
                    
                        
                            <li title='5' data-url='https://tc.skyone.host/blog/music/bilibili2018%20-%20%E8%87%B3%E5%B0%8A%E9%A9%AC%E7%94%B2.flac'></li>
                        
                    
                </ul>
            
        </div>
        
    <div id='gitalk-container' class="comment link"
		data-enable='true'
        data-ae='true'
        data-ci='d5e197ef955b7f3268e5'
        data-cs='7d4feed7a179ad28943b0865b7970814073145ad'
        data-r='blog-gitalk'
        data-o='skyone-wzw'
        data-a='skyone-wzw'
        data-d='false'
    >查看评论</div>


    </div>
    
        <div class='side'>
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AD%E6%96%AD%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%B3%95"><span class="toc-number">1.</span> <span class="toc-text">中断的基本实现方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BC%98%E9%9B%85%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%AD%E6%96%AD"><span class="toc-number">2.</span> <span class="toc-text">优雅的实现中断</span></a></li></ol>	
        </div>
    
</div>


    </div>
</div>
</body>

<script src="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>


<script src="//lib.baomitu.com/jquery/1.8.3/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/typed.js"></script>
<script src="/js/skyone.min.js"></script>


<link rel="stylesheet" href="/photoswipe/photoswipe.css">
<link rel="stylesheet" href="/photoswipe/default-skin/default-skin.css">


<script src="/photoswipe/photoswipe.min.js"></script>
<script src="/photoswipe/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>




</html>
